package net.vsame.url2sql.helper;

import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.vsame.url2sql.domain.InterceptorConfig;
import net.vsame.url2sql.domain.Url2SqlModel;
import net.vsame.url2sql.domain.Url2SqlModelChain;
import net.vsame.url2sql.domain.UrlConfig;

public class Url2SqlMappingHelper {
	
	private static Map<String, UrlConfig> urlSqlMap = new HashMap<String, UrlConfig>();
	private static List<InterceptorConfig> interceptorConfigs = new ArrayList<InterceptorConfig>();
	private static List<Url2SqlModel> models ;
	private static Map<String, Url2SqlModel> modelMap = new HashMap<String, Url2SqlModel>();
	
	/**
	 * 根据Url取得Sql
	 * @param url
	 * @return
	 */
	public static UrlConfig getConfig(String url){
		return urlSqlMap.get(url);
	}
	
	public static void addUrlConfig(UrlConfig urlConfig){
		urlSqlMap.put(urlConfig.getUrl(), urlConfig);
	}
	
	public static void addUrlConfig(String url, Class<?> clazz){
		Method[] ms = clazz.getDeclaredMethods();
		for(Method m : ms){
			if(Modifier.isPublic(m.getModifiers())){
				UrlConfig urlConfig = new UrlConfig();
				urlConfig.setClazz(clazz);
				urlConfig.setMethod(m);
				urlSqlMap.put(url + "/" + m.getName(), urlConfig);
			}
		}
	}
	
	public static void addInterceptorConfig(String regex, String js, int status){
		interceptorConfigs.add(new InterceptorConfig(regex, js, status));
	}
	public static Map<String, UrlConfig> getUrlSqlMap() {
		return urlSqlMap;
	}
	public static List<InterceptorConfig> getInterceptorConfigs() {
		return interceptorConfigs;
	}
	
	public static void reload(){
		urlSqlMap.clear();
		interceptorConfigs.clear();
		modelMap.clear();
		
		models = Url2SqlModelChain.reload();
		for (int i = 0; i < models.size(); i++) {
			Url2SqlModel m = models.get(i);
			String path = m.getContextPath();
			if(path != null){
				modelMap.put(path, m);
			}
		}
	}
	
	public static Url2SqlModel getModel(String contextPath){
		return modelMap.get(contextPath);
	}
}
